﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Galaktika.BI.Silverlight.ClientApp
{
    using Galaktika.BI.Silverlight.ClientApp.Services;
    using Galaktika.BI.Runtime;
    using Galaktika.BI.Runtime.Services;
    using Galaktika.BI.Extensibility;
    using Ranet.AgOlap.Features;
    using Ranet.AgOlap.Controls.ContextMenu;
    using System.Globalization;
    using Galaktika.BI.Silverlight.Services;
    using System.Windows.Browser;
    using Galaktika.BI.Silverlight.Controls;

    public partial class App : Application
    {
        #region SimpleServiceProvider
        private class SimpleServiceProvider : IServiceProvider
        {
            Dictionary<Type, object> m_Container;
            public SimpleServiceProvider()
            {
                m_Container = new Dictionary<Type, object>();
            }

            public void AddService(Type type, object instance)
            {
                m_Container.Add(type, instance);
            }

            public void RemoveService(Type type)
            {
                m_Container.Remove(type);
            }

            #region IServiceProvider Members

            public T GetService<T>()
                where T : class
            {
                object res;
                m_Container.TryGetValue(typeof(T), out res);

                return res as T;
            }

            public object GetService(Type type)
            {
                object res;
                m_Container.TryGetValue(type, out res);

                return res;
            }

            #endregion
        }
        #endregion

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            //this.ExecutionStateChanged += new EventHandler(App_ExecutionStateChanged);

            InitializeComponent();
            //Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru");
        }

        void App_ExecutionStateChanged(object sender, EventArgs e)
        {
            //if (this.ExecutionState == ExecutionStates.DetachedUpdatesAvailable)
            //{
            //    MessageBox.Show(Localization.Msg_NewerVersionAvailable);
            //}
        }

        private SimpleServiceProvider m_Services = new SimpleServiceProvider();
        public T GetService<T>()
            where T: class
        {
            return m_Services.GetService<T>();
        }

        public object GetService(Type type)
        {
            return m_Services.GetService(type);
        }

        //public IServiceProvider ServiceProvider
        //{
        //    get
        //    {
        //        return m_Services;
        //    }
        //}

        public static App CurrentApp
        {
            get
            {
                return (App)Application.Current;
            }
        }

        public IFormContainer Root
        {
            get
            {
                return m_PageRoot;
            }
        }

        public void AddService(Type type, object instance)
        {
            m_Services.AddService(type, instance);
        }

        private MetaContainer m_Metadata;
        public void Initialize(MetaContainer metadata)
        {
            m_Metadata = metadata;
			this.Binder.InitializeMatadata(metadata); 
			//this.Root.Initialize(metadata.Workstations);
        }

        public void InitializeRoot()
        {
            this.Root.Initialize(m_Metadata.Workstations);
        }

        public DataBinder Binder { get; private set; }

		private IFormContainer m_PageRoot;
        private void Application_Startup(object sender, StartupEventArgs e)
		{
            Galaktika.BI.Silverlight.Commands.CommandDispatcher.RegisterDispatcher<Galaktika.BI.Silverlight.ClientApp.Web.Commands.BmCommandDispatcher>();

            // init ServicManager 
            var baseUrl = Ranet.AgOlap.Services.ServiceManager.BaseAddress;
            Galaktika.BI.ImageLibrary.Identity.Check();

            var p = e.InitParams.ContainsKey("cardId") ? new Page(e.InitParams["cardId"], e.InitParams) : new Page();
            m_PageRoot = p;
            p.RefreshConnectivityView();

			this.RootVisual = m_PageRoot.RootControl;
            this.ShowCurrentUserName(((Page)m_PageRoot.RootControl).txtUserName);
            Ranet.AgOlap.Features.ScrollViewerMouseWheelSupport.Initialize(m_PageRoot.RootControl);
            this.EnableContextMenuSupport();
            m_Services.AddService(typeof(IOutputService), new OutputService(m_Services));
            m_Services.AddService(typeof(IFormNavigator), this.Root.Navigator);
            m_Services.AddService(typeof(IAppManager), this.Root.AppManager);
            m_Services.AddService(typeof(ITabPageFormResolver), this.Root.TabPageFormResolver);
            m_Services.AddService(typeof(IExecutionContext), new ExecutionContext());
            m_Services.AddService(typeof(IScriptEngine), new ScriptEngineImpl());
            m_Services.AddService(typeof(IScreenModeService), new ScreenModeService());
            m_Services.AddService(typeof(IAdomdSessionProvider), new AdomdSessionProvider());
            ScriptEngine.Initialize(this.GetService<IScriptEngine>());
            QueryExecutionManager.Initialize(((Page)m_PageRoot.RootControl).outputControl.QueryViewer.ViewModel);
			
			this.Binder = new DataBinder(m_Services);

            //if (this.RunningOffline && !System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            //{
            //    MessageBox.Show(Localization.Msg_NeworkConnectionUnavailable);
            //}
            //else
            //{
                //Downloader.DownloadAll();

            var taskMgr = this.GetService<IUserTaskManager>();
            if (taskMgr != null)
            {
                var dispatcher = p.Dispatcher;
                taskMgr.RunTaskAsync(
                    Localization.AppTask_CheckingForUpdates,
                    _=> ClientAppHolder.LoadClientApp(dispatcher));
            }
            //}
        }

        private void ShowCurrentUserName(TextBlock txtUserName)
        {
            if (HtmlPage.IsEnabled)
            {
                try
                {
                    ScriptObject getUserNameFunc = HtmlPage.Window.GetProperty("getCurrentUserName") as ScriptObject;
                    if (getUserNameFunc != null)
                    {
                        object usrName = getUserNameFunc.InvokeSelf();
                        if (usrName != null)
                        {
                            txtUserName.Text = usrName.ToString();
                        }
                    }
                }
                catch (Exception exc)
                {
                    txtUserName.Text = exc.Message;
                    ToolTipService.SetToolTip(txtUserName, new StyledToolTip() { Content = exc.ToString() });
                }
            }
        }

        internal void LogError(Exception exc)
        {
            IOutputService output = this.GetService<IOutputService>();
            if (output != null)
            {
                output.WriteException(exc);
            }
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.ToString();
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
